import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Typography, 
  Paper, 
  Grid, 
  Divider, 
  Table, 
  TableBody, 
  TableCell, 
  TableContainer, 
  TableHead, 
  TableRow, 
  Chip, 
  CircularProgress,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Tabs,
  Tab
} from '@mui/material';
import { 
  Download as DownloadIcon, 
  FileCopy as FileTextIcon, 
  CalendarToday as CalendarIcon, 
  People as UsersIcon, 
  BarChart as BarChartIcon,
  PieChart as PieChartIcon,
  TrendingUp as TrendingUpIcon
} from '@mui/icons-material';
import apiRequest from '../utils/api';

// 模拟数据 - 实际项目中应从API获取
const mockUserStats = [
  {
    userId: 101,
    userName: '张三',
    totalFiles: 12,
    totalDownloads: 28,
    fileTypes: {
      xlsx: 8,
      pdf: 3,
      csv: 1
    },
    recentActivity: [
      { date: '2024-08-01', filesAdded: 2, downloads: 3 },
      { date: '2024-08-08', filesAdded: 1, downloads: 5 },
      { date: '2024-08-15', filesAdded: 3, downloads: 7 },
      { date: '2024-08-22', filesAdded: 2, downloads: 4 },
      { date: '2024-08-29', filesAdded: 1, downloads: 2 }
    ],
    mostDownloadedFile: {
      name: '车辆维修记录_20240715_张三.xlsx',
      downloads: 12
    }
  },
  {
    userId: 102,
    userName: '李四',
    totalFiles: 8,
    totalDownloads: 15,
    fileTypes: {
      xlsx: 5,
      pdf: 2,
      csv: 1
    },
    recentActivity: [
      { date: '2024-08-02', filesAdded: 1, downloads: 2 },
      { date: '2024-08-09', filesAdded: 2, downloads: 3 },
      { date: '2024-08-16', filesAdded: 1, downloads: 2 },
      { date: '2024-08-23', filesAdded: 1, downloads: 4 },
      { date: '2024-08-30', filesAdded: 1, downloads: 1 }
    ],
    mostDownloadedFile: {
      name: '故障诊断报告_20240805_李四.pdf',
      downloads: 8
    }
  },
  {
    userId: 103,
    userName: '王五',
    totalFiles: 5,
    totalDownloads: 9,
    fileTypes: {
      xlsx: 3,
      pdf: 1,
      csv: 1
    },
    recentActivity: [
      { date: '2024-08-03', filesAdded: 1, downloads: 1 },
      { date: '2024-08-10', filesAdded: 1, downloads: 2 },
      { date: '2024-08-17', filesAdded: 1, downloads: 1 },
      { date: '2024-08-24', filesAdded: 1, downloads: 2 },
      { date: '2024-08-31', filesAdded: 1, downloads: 2 }
    ],
    mostDownloadedFile: {
      name: '车辆保养提醒_20240820_王五.csv',
      downloads: 5
    }
  }
];

// 模拟总体统计数据
const mockOverallStats = {
  totalUsers: 3,
  totalFiles: 25,
  totalDownloads: 52,
  averageFilesPerUser: 8.33,
  averageDownloadsPerFile: 2.08
};

// 模拟文件类型分布
const mockFileTypeDistribution = {
  xlsx: 16,
  pdf: 6,
  csv: 3
};

// 模拟时间趋势数据
const mockTimeTrendData = [
  { date: '2024-06', files: 5, downloads: 8 },
  { date: '2024-07', files: 12, downloads: 24 },
  { date: '2024-08', files: 8, downloads: 20 }
];

const ServiceProviderInfoDisplay = () => {
  const [userStats, setUserStats] = useState([]);
  const [overallStats, setOverallStats] = useState(null);
  const [fileTypeDistribution, setFileTypeDistribution] = useState(null);
  const [timeTrendData, setTimeTrendData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [selectedUser, setSelectedUser] = useState('all');
  const [activeTab, setActiveTab] = useState(0);

  // 加载数据
  useEffect(() => {
    const loadStats = async () => {
      try {
        setLoading(true);
        setError('');
        
        // 实际项目中，这里应该从API获取数据
        // const userStatsResponse = await apiRequest.get('/api/service-provider/user-stats');
        // const overallStatsResponse = await apiRequest.get('/api/service-provider/overall-stats');
        // const fileTypeResponse = await apiRequest.get('/api/service-provider/file-type-distribution');
        // const timeTrendResponse = await apiRequest.get('/api/service-provider/time-trend');
        
        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 1000));
        setUserStats(mockUserStats);
        setOverallStats(mockOverallStats);
        setFileTypeDistribution(mockFileTypeDistribution);
        setTimeTrendData(mockTimeTrendData);
      } catch (err) {
        setError('加载统计数据失败，请重试');
        console.error('加载统计数据失败:', err);
      } finally {
        setLoading(false);
      }
    };

    loadStats();
  }, []);

  // 处理标签页切换
  const handleTabChange = (event, newValue) => {
    setActiveTab(newValue);
  };

  // 获取筛选后的用户数据
  const getFilteredData = () => {
    if (selectedUser === 'all') {
      return userStats;
    }
    return userStats.filter(user => user.userId.toString() === selectedUser);
  };

  // 渲染简单的条形图（无外部库）
  const renderSimpleBarChart = (data, labelProp, valueProp, label) => {
    const maxValue = Math.max(...data.map(item => item[valueProp]), 1);
    const barWidth = 60;
    
    return (
      <Box sx={{ height: 200, mt: 2 }}>
        <Grid container spacing={2} sx={{ height: '100%' }}>
          {data.map((item, index) => {
            const height = (item[valueProp] / maxValue) * 150;
            return (
              <Grid item xs={6} sm={4} md={3} key={index} sx={{ position: 'relative' }}>
                <Box 
                  sx={{
                    position: 'absolute',
                    bottom: 0,
                    width: barWidth,
                    height: height,
                    bgcolor: 'primary.main',
                    left: '50%',
                    transform: 'translateX(-50%)',
                    borderRadius: '4px 4px 0 0'
                  }}
                />
                <Box sx={{ position: 'absolute', bottom: -25, left: 0, right: 0, textAlign: 'center' }}>
                  <Typography variant="caption" fontWeight="bold">{item[labelProp]}</Typography>
                </Box>
                <Box sx={{ position: 'absolute', bottom: height + 5, left: 0, right: 0, textAlign: 'center' }}>
                  <Typography variant="body2" fontWeight="bold">{item[valueProp]}</Typography>
                </Box>
              </Grid>
            );
          })}
        </Grid>
        <Typography variant="subtitle2" align="center" mt={2} color="text.secondary">
          {label}
        </Typography>
      </Box>
    );
  };

  // 渲染简单的饼图（无外部库）
  const renderSimplePieChart = (distribution, title) => {
    const total = Object.values(distribution).reduce((sum, count) => sum + count, 0);
    const colors = { xlsx: '#4caf50', pdf: '#f44336', csv: '#2196f3', other: '#ff9800' };
    
    return (
      <Box sx={{ mt: 2 }}>
        <Typography variant="subtitle1" align="center" gutterBottom>{title}</Typography>
        <Box sx={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center', gap: 2 }}>
          {Object.entries(distribution).map(([type, count]) => {
            const percentage = ((count / total) * 100).toFixed(1);
            return (
              <Box key={type} sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <Box 
                  sx={{
                    width: 16,
                    height: 16,
                    bgcolor: colors[type] || colors.other,
                    borderRadius: 2
                  }}
                />
                <Typography variant="body2">
                  {type.toUpperCase()}: {count} ({percentage}%)
                </Typography>
              </Box>
            );
          })}
        </Box>
      </Box>
    );
  };

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h4" gutterBottom>信息展示与数据分析</Typography>
      <Typography variant="body1" color="text.secondary" gutterBottom>
        按用户展示下载文件数据，帮助服务商分析和提炼有价值的信息
      </Typography>
      <Divider sx={{ mb: 4 }} />

      {/* 筛选区域 */}
      <Box sx={{ mb: 4, display: 'flex', justifyContent: 'flex-end' }}>
        <FormControl sx={{ minWidth: 150 }}>
          <InputLabel>选择用户</InputLabel>
          <Select
            value={selectedUser}
            label="选择用户"
            onChange={(e) => setSelectedUser(e.target.value)}
          >
            <MenuItem value="all">全部用户</MenuItem>
            {userStats.map(user => (
              <MenuItem key={user.userId} value={user.userId}>{user.userName}</MenuItem>
            ))}
          </Select>
        </FormControl>
      </Box>

      {/* 加载状态 */}
      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', p: 8 }}>
          <CircularProgress />
        </Box>
      ) : error ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', p: 8, color: 'error.main' }}>
          <Typography variant="h6">{error}</Typography>
        </Box>
      ) : (
        <>
          {/* 总体统计卡片 */}
          {overallStats && (
            <Grid container spacing={3} sx={{ mb: 4 }}>
              <Grid item xs={12} sm={6} md={3}>
                <Paper elevation={2} sx={{ p: 3, display: 'flex', alignItems: 'center', gap: 2 }}>
                  <Box sx={{ p: 2, bgcolor: 'primary.light', borderRadius: '50%' }}>
                    <UsersIcon color="primary" />
                  </Box>
                  <Box>
                    <Typography variant="subtitle2" color="text.secondary">用户总数</Typography>
                    <Typography variant="h5" fontWeight="bold">{overallStats.totalUsers}</Typography>
                  </Box>
                </Paper>
              </Grid>
              <Grid item xs={12} sm={6} md={3}>
                <Paper elevation={2} sx={{ p: 3, display: 'flex', alignItems: 'center', gap: 2 }}>
                  <Box sx={{ p: 2, bgcolor: 'primary.light', borderRadius: '50%' }}>
                    <FileTextIcon color="primary" />
                  </Box>
                  <Box>
                    <Typography variant="subtitle2" color="text.secondary">文件总数</Typography>
                    <Typography variant="h5" fontWeight="bold">{overallStats.totalFiles}</Typography>
                  </Box>
                </Paper>
              </Grid>
              <Grid item xs={12} sm={6} md={3}>
                <Paper elevation={2} sx={{ p: 3, display: 'flex', alignItems: 'center', gap: 2 }}>
                  <Box sx={{ p: 2, bgcolor: 'primary.light', borderRadius: '50%' }}>
                    <DownloadIcon color="primary" />
                  </Box>
                  <Box>
                    <Typography variant="subtitle2" color="text.secondary">下载总数</Typography>
                    <Typography variant="h5" fontWeight="bold">{overallStats.totalDownloads}</Typography>
                  </Box>
                </Paper>
              </Grid>
              <Grid item xs={12} sm={6} md={3}>
                <Paper elevation={2} sx={{ p: 3, display: 'flex', alignItems: 'center', gap: 2 }}>
                  <Box sx={{ p: 2, bgcolor: 'primary.light', borderRadius: '50%' }}>
                    <TrendingUpIcon color="primary" />
                  </Box>
                  <Box>
                    <Typography variant="subtitle2" color="text.secondary">平均文件下载量</Typography>
                    <Typography variant="h5" fontWeight="bold">{overallStats.averageDownloadsPerFile.toFixed(1)}</Typography>
                  </Box>
                </Paper>
              </Grid>
            </Grid>
          )}

          {/* 标签页导航 */}
          <Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 3 }}>
            <Tabs value={activeTab} onChange={handleTabChange} variant="scrollable" scrollButtons="auto">
              <Tab label="用户数据统计" icon={<BarChartIcon />} iconPosition="start" />
              <Tab label="文件类型分布" icon={<PieChartIcon />} iconPosition="start" />
              <Tab label="时间趋势分析" icon={<CalendarIcon />} iconPosition="start" />
            </Tabs>
          </Box>

          {/* 各标签页内容 */}
          {activeTab === 0 && (
            <>
              {/* 用户文件和下载统计 */}
              <Paper elevation={2} sx={{ p: 3, mb: 4 }}>
                <Typography variant="h6" gutterBottom>用户文件与下载统计</Typography>
                {renderSimpleBarChart(
                  getFilteredData(),
                  'userName',
                  'totalFiles',
                  '各用户文件数量'
                )}
                {renderSimpleBarChart(
                  getFilteredData(),
                  'userName',
                  'totalDownloads',
                  '各用户文件总下载次数'
                )}
              </Paper>

              {/* 各用户详细统计表格 */}
              <Paper elevation={2} sx={{ p: 3 }}>
                <Typography variant="h6" gutterBottom>用户详细统计信息</Typography>
                <TableContainer>
                  <Table aria-label="用户统计表格">
                    <TableHead>
                      <TableRow sx={{ backgroundColor: 'grey.100' }}>
                        <TableCell>用户名</TableCell>
                        <TableCell>文件总数</TableCell>
                        <TableCell>总下载次数</TableCell>
                        <TableCell>XLSX文件</TableCell>
                        <TableCell>PDF文件</TableCell>
                        <TableCell>CSV文件</TableCell>
                        <TableCell>最受欢迎文件</TableCell>
                        <TableCell>最受欢迎文件下载数</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {getFilteredData().map((user) => (
                        <TableRow key={user.userId} hover>
                          <TableCell>
                            <Typography fontWeight="bold">{user.userName}</Typography>
                          </TableCell>
                          <TableCell>{user.totalFiles}</TableCell>
                          <TableCell>{user.totalDownloads}</TableCell>
                          <TableCell>{user.fileTypes.xlsx || 0}</TableCell>
                          <TableCell>{user.fileTypes.pdf || 0}</TableCell>
                          <TableCell>{user.fileTypes.csv || 0}</TableCell>
                          <TableCell>
                            <Chip 
                              label={user.mostDownloadedFile.name.length > 20 
                                ? user.mostDownloadedFile.name.substring(0, 20) + '...' 
                                : user.mostDownloadedFile.name}
                              size="small"
                              title={user.mostDownloadedFile.name}
                            />
                          </TableCell>
                          <TableCell>{user.mostDownloadedFile.downloads}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </TableContainer>
              </Paper>
            </>
          )}

          {activeTab === 1 && (
            <Paper elevation={2} sx={{ p: 3 }}>
              <Typography variant="h6" gutterBottom>文件类型分布</Typography>
              {fileTypeDistribution && (
                renderSimplePieChart(fileTypeDistribution, '所有文件类型分布')
              )}
              
              {/* 按用户的文件类型分布 */}
              <Divider sx={{ my: 4 }} />
              <Typography variant="h6" gutterBottom>按用户的文件类型分布</Typography>
              <Grid container spacing={3}>
                {getFilteredData().map(user => (
                  <Grid item xs={12} md={6} key={user.userId}>
                    <Paper elevation={1} sx={{ p: 2 }}>
                      <Typography variant="subtitle1" gutterBottom>{user.userName}</Typography>
                      {renderSimplePieChart(user.fileTypes, `${user.userName}的文件类型分布`)}]
                    </Paper>
                  </Grid>
                ))}
              </Grid>
            </Paper>
          )}

          {activeTab === 2 && (
            <Paper elevation={2} sx={{ p: 3 }}>
              <Typography variant="h6" gutterBottom>文件与下载时间趋势</Typography>
              {renderSimpleBarChart(
                timeTrendData,
                'date',
                'files',
                '每月新增文件数量'
              )}
              {renderSimpleBarChart(
                timeTrendData,
                'date',
                'downloads',
                '每月文件下载次数'
              )}
            </Paper>
          )}
        </>
      )}
    </Box>
  );
};

export default ServiceProviderInfoDisplay;